package com.las.bot.cmd.lol;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.las.annotation.BotCmd;
import com.las.bot.dao.LolAreaDao;
import com.las.bot.dao.LolSettingDao;
import com.las.bot.dao.LolTierDao;
import com.las.cmd.BaseCommand;
import com.las.cmd.BaseNonCommand;
import com.las.utils.mirai.CmdUtil;
import com.model.LolArea;
import com.model.LolSetting;
import com.model.LolTier;
import com.utils.JsonUtils;
import com.utils.StrUtils;
import com.utils.lol.LOLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@BotCmd(funName = "LOL", isMatch = false)
public class LoLAreaSearchCommand extends BaseNonCommand {

    private Logger logger = LoggerFactory.getLogger(LoLAreaSearchCommand.class);

    private String[] tierStr = {"Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ"};

    @Autowired
    private LolSettingDao settingDao;

    @Autowired
    private LolAreaDao areaDao;

    @Autowired
    private LolTierDao tierDao;


    @Override
    public void execute(JSONObject o, Long userId, Long id, Integer type, String command, ArrayList<String> args) {
        if (command.startsWith("#") || command.startsWith("/段位")) {
            command = command.replaceAll("/", "").trim();
            command = command.replaceAll("段位", "").trim();
            command = command.replaceAll("#", "").trim();
            // 然后检查指令前面的信息是否所选区域
            List<LolArea> areaList = areaDao.findList();
            List<String> areas = areaList.stream().map(LolArea::getAreaName).collect(Collectors.toList());
            Map<String, LolArea> areaMap = areaList.stream().collect(Collectors.toMap(LolArea::getAreaName, v -> v));
            String nowA = "";
            for (String area : areas) {
                if (command.startsWith(area)) {
                    nowA = area;
                    break;
                }
            }
            if (StrUtil.isNotBlank(nowA)) {
                LolArea nowLolArea = areaMap.get(nowA);
                String userName = "";
                if (args.size() > 0) {
                    String p = command.replaceAll(nowLolArea.getAreaName(), "");
                    userName = p.toLowerCase().trim();
                    if (StrUtil.isBlank(userName)) {
                        CmdUtil.sendMessage("请在指令后带玩家名称", userId, id, type);
                        return;
                    }
                }
                LolSetting setting = settingDao.findByName("cookie");
                if (ObjectUtil.isNotNull(setting)) {
                    String value = setting.getValue();
                    String result = LOLUtils.getInstanceByCookie(value).searchPlayer(userName);
                    logger.info("得到LOL玩家信息：" + result);
                    JSONObject userObj = JsonUtils.getJsonObjectByJsonString(result);
                    JSONArray players = userObj.getJSONArray("players");

                    String cookie = setting.getValue();
                    StringBuilder sb = new StringBuilder();
                    if (null != players) {
                        if (players.size() == 0) {
                            CmdUtil.sendMessage("该玩家不存在，也可能是wegame炸了，你试试用wegame搜索看看？", userId, id, type);
                            return;
                        }
                        sb.append("玩家：").append(userName).append("\n");
                        JSONObject maxObj = null;
                        for (int i = 0; i < players.size(); i++) {
                            JSONObject player = players.getJSONObject(i);
                            int area = player.getIntValue("area");
                            if (area == nowLolArea.getId()) {
                                maxObj = player;
                                break;
                            }
                        }
                        if (ObjectUtil.isNotNull(maxObj)) {
                            String openid = maxObj.getString("openid");
                            int area = maxObj.getIntValue("area");
                            int level = maxObj.getIntValue("level");
                            LolArea lolArea = areaDao.findById(area);
                            sb.append("区域：").append(lolArea.getAreaName()).append("\n");
                            sb.append("等级：").append(level).append("\n");

                            String json = LOLUtils.getInstanceByCookie(cookie).getUserInfo(openid, area);
                            JSONObject infoObj = JsonUtils.getJsonObjectByJsonString(json);
                            if (ObjectUtil.isNotNull(infoObj.getJSONObject("battle_count"))) {
                                JSONObject battle = infoObj.getJSONObject("battle_count");
                                sb.append("匹配对局(胜/负)：").append(battle.getIntValue("total_match_wins")).append("/").append(battle.getIntValue("total_match_losts")).append("\n");
                                sb.append("乱斗对局(胜/负)：").append(battle.getIntValue("total_arm_wins")).append("/").append(battle.getIntValue("total_arm_losts")).append("\n");
                                JSONArray seasonList = infoObj.getJSONArray("season_list");
                                if (CollectionUtil.isNotEmpty(seasonList)) {
                                    JSONObject season = seasonList.getJSONObject(0);

                                    LolTier tier = tierDao.findByTierId(season.getIntValue("tier"));
                                    String tierShow;
                                    if (ObjectUtil.isNull(tier)) {
                                        tierShow = "暂无段位";
                                    } else {
                                        if (tier.getTier() == 0 || tier.getTier() == 6 || tier.getTier() == 7) {
                                            tierShow = tier.getTierName();
                                        } else {
                                            tierShow = tier.getTierName() + tierStr[season.getIntValue("queue")];
                                        }
                                    }

                                    LolTier teamTier = tierDao.findByTierId(season.getIntValue("team_tier"));
                                    String teamShow;
                                    if (ObjectUtil.isNull(teamTier)) {
                                        teamShow = "暂无段位";
                                    } else {
                                        if (teamTier.getTier() == 0 || teamTier.getTier() == 6 || teamTier.getTier() == 7) {
                                            teamShow = tier.getTierName();
                                        } else {
                                            teamShow = teamTier.getTierName() + tierStr[season.getIntValue("team_queue")];
                                        }
                                    }
                                    sb.append("单双排位(胜/负)：").append(season.getIntValue("wins")).append("/").append(season.getIntValue("losses")).append("\n");
                                    sb.append("单双段位：").append(tierShow).append("、胜点：").append(season.getIntValue("win_point")).append("点\n");
                                    sb.append("灵活排位(胜/负)：").append(season.getIntValue("team_wins")).append("/").append(season.getIntValue("team_losses")).append("\n");
                                    sb.append("灵活段位：").append(teamShow).append("、胜点：").append(season.getIntValue("team_win_point")).append("点\n");

                                }
                            } else {
                                sb.append("该玩家设置了权限！无法查看更多数据");
                            }

                        } else {
                            sb.append("该玩家不在 ").append(nowLolArea.getAreaName()).append(" 请检查区域是否正确");
                        }
                    }
                    if (StrUtils.isNotEmpty(sb.toString())) {
                        CmdUtil.sendMessage(sb.toString(), userId, id, type);
                    }
                }
            }


        }
    }


}
